<?php
namespace Com\Pay;
class AlipayPay{
	private $alipay_config = array();
	public function __construct($alipay_config = array()){
		$this->alipay_config = array(
		        'seller_email' => $alipay_config['appid'],
				'partner' => $alipay_config['mch_id'],
				'key' => $alipay_config['mch_key'],
				'notify_url' => 'http://' . $_SERVER['HTTP_HOST'].'/Api/NotifyCallback/AlipayPay',
				'sign_type' => 'MD5',
				'input_charset' => 'UTF-8',
				'cacert' => LIB_PATH .'/Com/ALIPAY/cacert.pem',
				'transport' => 'http',
				'payment_type' => '1',
				'service' => 'create_direct_pay_by_user'
		);
	}

	public function alipayPay($payInfo){
		require_once(LIB_PATH . "Com/ALIPAY/lib/alipay_submit.class.php");
		//构造要请求的参数数组，无需改动
		$parameter = array(
				"service"       => $this->alipay_config['service'],
				"partner"       => $this->alipay_config['partner'],
				"payment_type"	=> $this->alipay_config['payment_type'],
				"seller_email"	=> $this->alipay_config['seller_email'],
				"notify_url"	=> $this->alipay_config['notify_url'],
				"return_url"	=> $payInfo['return_url'],
				"out_trade_no"	=> $payInfo['ordernumber'],
				"subject"	=> 'KamengwangTest',
				"total_fee"	=> $payInfo['paymoney'],
				"body"	=> '商品测试',
				"_input_charset"	=> trim(strtolower($this->alipay_config['input_charset']))
		);
//            var_dump($parameter);die;
		//建立请求
		$alipaySubmit = new \Com\Alipay\AlipaySubmit($this->alipay_config);
		$html_text = $alipaySubmit->buildRequestForm($parameter,"get", "确认");
		return $html_text;
	}

	public function response(){
		require_once(LIB_PATH . "/Com/ALIPAY/lib/alipay_notify.class.php");
		//计算得出通知验证结果
		$alipayNotify = new \Com\Alipay\AlipayNotify($this->alipay_config);
		$verify_result = $alipayNotify->verifyNotify();
		if($verify_result) {
            if($_POST['trade_status'] == 'TRADE_SUCCESS') {
                return true;
            }
            return false; // 签名正确，但交易失败
		}
		else {
		    //验证失败
		    return false;
		}
	}

	public function CallbackReturn(){
        $alipayNotify = new \Com\Alipay\AlipayNotify($this->alipay_config);
        $verify_result = $alipayNotify->verifyReturn();
        if ($verify_result) {
            $out_trade_no = strip_tags($_GET['out_trade_no']);
            //支付宝交易号
            $trade_no = $_GET['trade_no'];
            //交易状态
            $trade_status = $_GET['trade_status'];
            if($trade_status == 'TRADE_FINISHED' || $trade_status == 'TRADE_SUCCESS') {
                $order = M('transaction')->field('callback_url')->where(array('out_trade_no' => $out_trade_no))->find();
                if($order) return true;
            }
        }
        return false;
    }
}